package ctf

import (
	"errors"
	"pdocker/tool/sql"

	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

func (t *TaskTable) Insert() bool {
	isExist := t.Select()
	// 判断是否存在
	// 如果存在，返回false
	if isExist {
		return !isExist
	} else {
		result := sql.PgDB.Create(t)
		if result.Error != nil {
			log.Errorln(result.Error)
			return false
		}
		return true
	}
}

func (t *TaskTable) Update(TimeStamp int64) {
	t.Data.Task.DestroyTimeStamp = TimeStamp
	log.Debug(t)
	err := sql.PgDB.Model(t).Update("data", t.Data)
	if err != nil {
		log.Errorln(err)
	}
}

func (t *TaskTable) Delete() {
	log.Infof("==执行Model.Delete %+v", t)
	sql.PgDB.Delete(t)
}

func (t *TaskTable) Select() bool {
	// Todo: need some guard
	result := sql.PgDB.First(t)
	log.Debugf("First() result %v", result)
	if result.Error != nil {
		log.Warningln(result.Error)
	}
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return false
	}
	return true
}

func (*TaskTable) TableName() string {
	return "ctf_task_table"
}
